package PrintAB;

class MyCondition3 {
    private int number = 0;

    //⽼版写法
    public synchronized void printA() throws Exception {
        //1.判断
        if (number != 0) {
            this.wait();
        }
        //2.⼲活
        number++;
        System.out.println(Thread.currentThread().getName() + "\t" + "A");
        //3通知
        this.notifyAll();
    }

    public synchronized void printB() throws Exception {
        //1.判断
        if (number == 0) {
            this.wait();
        }
        //2.⼲活
        number--;
        System.out.println(Thread.currentThread().getName() + "\t" + "B");
        //3通知
        this.notifyAll();
    }
}

public class PrintBySynchronized {
    public static void main(String[] args) {
        MyCondition3 myCondition = new MyCondition3();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    myCondition.printA();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "线程A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    myCondition.printB();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "线程B").start();
    }
}
